package com.jp.knowledge.command;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;

import com.jp.knowledge.util.L;

import java.io.Serializable;
import java.lang.reflect.Constructor;

/**
 * Created by 528787067@qq.com on 2017/6/17.
 *
 * 抽象命令
 */

public abstract class Command {

	/**
	 * 创建命令对象
	 *
	 * @param command		命令参数
	 * @return				返回命令对象
	 */
	private static final String COMMAND_PACKAGE_PATH = "com.jp.knowledge.command.implement";
	@NonNull
	public static Command create(@NonNull final String command, @NonNull CommandReceiver receivert){
		Command commandObject = null;
		try {
			Class clazz = Class.forName(COMMAND_PACKAGE_PATH + "." + command);
			Class[] paramTypes = { CommandReceiver.class };
			Constructor constructor = clazz.getConstructor(paramTypes);
			Object[] params = { receivert };
			commandObject = (Command) constructor.newInstance(params);
		} catch (Exception e) {
			L.e(e.getMessage());
		} finally {
			if(commandObject == null)
				commandObject = new Command(receivert){
					@Override
					public void execute() {
						L.e("Command Object Create Fail ---> " + toString());
					}
				};
		}
		return commandObject;
	}

	protected Context context;
	protected String companyId;
	protected String recordId;
	protected String messageId;
	protected String parameterId;
	protected Bundle extra;

	public Command(@NonNull CommandReceiver receivert){
		context = receivert.getContext();
		companyId = receivert.getCommpanyId();
		recordId = receivert.getRecordId();
		messageId = receivert.getMessageId();
		parameterId = receivert.getParameterId();
		extra = receivert.getExtra();
	}

	protected Intent createIntent(@NonNull  Class<? extends Activity> activityClass){
		Intent intent = new Intent(context, activityClass);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
		intent.putExtra("companyId", companyId);
		intent.putExtra("recordId", recordId);
		intent.putExtra("messageId", messageId);
		intent.putExtra("parameterId", parameterId);
		intent.putExtra("extra", extra);
		intent.putExtra("command", getClass().getSimpleName());
		return intent;
	}

	protected void startActivity(@NonNull Intent intent){
		context.startActivity(intent);
	}

	@Override
	public String toString() {
		return "{" +
					"\"command\":"			+ getClass().getSimpleName()					+ "," +
					"\"companyId\":"		+ companyId									+ "," +
					"\"recordId\":"		+ recordId										+ "," +
					"\"messageId\":"		+ messageId									+ "," +
					"\"parameterId\":"	+ parameterId									+ "," +
					"\"extra\":"			+ (extra == null ? "null" : extra.toString())	+
				"}";
	}

	/**
	 * 执行命令
	 */
	public abstract void execute();
}
